package com.xsomnus.open.imv2.foo.server.handler;

import com.xsomnus.open.imv2.protocol.request.CreateGroupRequestPacket;
import com.xsomnus.open.imv2.protocol.response.CreateGroupResponsePacket;
import com.xsomnus.open.imv2.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019-04-25 22:39
 * 既然选择了远方,便只顾风雨兼程
 */
public class CreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket createGroupRequestPacket) throws Exception {
        List<String> userIdList = createGroupRequestPacket.getUserIdList();
        List<String> userNameList = new ArrayList<>();
        //(1) 创建一个channel分组
        ChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());
        //(2) 筛选出带加入群聊的用户的channel和username
        for (String userId : userIdList) {
            Channel channel = SessionUtil.getChannel(userId);
            if (channel != null) {
                channelGroup.add(channel);
                userNameList.add(SessionUtil.getSession(channel).getUsername());
            }
        }

        // (3) 创建群聊结果
        CreateGroupResponsePacket response = new CreateGroupResponsePacket();
        response.setSuccess(true);
        String groupId = UUID.randomUUID().toString().split("-")[0];
        response.setGroupId(groupId);
        response.setUsernameList(userNameList);

        // (4) 给每个客户端发送拉群通知
        channelGroup.writeAndFlush(response);

        System.out.println("群创建成功, id为[" + response.getGroupId() + "], ");
        System.out.println("群里面有：" + response.getUsernameList());

        // (5) 保存群组信息
        SessionUtil.bindChannelGroup(groupId, channelGroup);
    }
}
